import 'package:flutter/material.dart';
import 'package:photo_manager/photo_manager.dart';
import 'widgets/mediaGrid.dart';
import '../publish/publishPage.dart';

class MediaPickerPage extends StatefulWidget {
  final List<AssetEntity> initialSelectedPhotos;
  final List<AssetEntity> initialSelectedVideos;
  final int? taskConfigId;
  final int? taskRecordId;
  final int networkImageCount;
  final bool isFromPublishPage;

  const MediaPickerPage({
    Key? key,
    this.initialSelectedPhotos = const [],
    this.initialSelectedVideos = const [],
    this.taskConfigId,
    this.taskRecordId,
    this.networkImageCount = 0,
    this.isFromPublishPage = false,
  }) : super(key: key);

  @override
  State<MediaPickerPage> createState() => _MediaPickerPageState();
}

class _MediaPickerPageState extends State<MediaPickerPage> {
  List<AssetEntity> photoList = [];
  List<AssetEntity> videoList = [];
  List<int> selectedPhotoIndexes = [];
  List<int> selectedVideoIndexes = [];
  int maxPhotoSelect = 18;
  int maxVideoSelect = 1;
  int tabIndex = 0;
  bool isLoading = true;

  int _nextPhotoOrder = 1;
  int _nextVideoOrder = 1;

  late ValueNotifier<SelectionState> photoSelectionNotifier;
  late ValueNotifier<SelectionState> videoSelectionNotifier;

  @override
  void initState() {
    super.initState();
    _nextPhotoOrder = 1 + widget.networkImageCount;

    print('=== MediaPickerPage 接收到的参数 ===');
    print('taskConfigId: ${widget.taskConfigId}');
    print('taskRecordId: ${widget.taskRecordId}');
    print('================================');
    _fetchAllAssets();

    photoSelectionNotifier = ValueNotifier<SelectionState>(
        SelectionState(selectedIndexes: [], orderMap: {}));
    videoSelectionNotifier = ValueNotifier<SelectionState>(
        SelectionState(selectedIndexes: [], orderMap: {}));
  }

  @override
  void dispose() {
    photoSelectionNotifier.dispose();
    videoSelectionNotifier.dispose();
    super.dispose();
  }

  Future<void> _fetchAllAssets() async {
    final PermissionState ps = await PhotoManager.requestPermissionExtend();
    if (!ps.isAuth) {
      setState(() => isLoading = false);
      return;
    }

    List<AssetPathEntity> albums = await PhotoManager.getAssetPathList(
      type: RequestType.all,
      onlyAll: true,
    );

    if (albums.isNotEmpty) {
      AssetPathEntity album = albums[0];
      final totalCount = await album.assetCountAsync;

      print('总媒体文件数量: $totalCount');

      // 一次性加载所有媒体文件
      final List<AssetEntity> allAssets =
          await album.getAssetListRange(start: 0, end: totalCount);

      setState(() {
        photoList = allAssets.where((e) => e.type == AssetType.image).toList();
        videoList = allAssets.where((e) => e.type == AssetType.video).toList();
        isLoading = false;

        print('照片数量: ${photoList.length}');
        print('视频数量: ${videoList.length}');

        // 恢复之前的选择
        _restorePreviousSelections();
      });
    } else {
      setState(() => isLoading = false);
    }
  }

  void _restorePreviousSelections() {
    if (widget.initialSelectedPhotos.isNotEmpty) {
      final selectedIndexes = <int>[];
      final orderMap = <int, int>{};
      int order = 1 + widget.networkImageCount;

      for (final photo in widget.initialSelectedPhotos) {
        final index = photoList.indexWhere((p) => p.id == photo.id);
        if (index != -1) {
          selectedIndexes.add(index);
          orderMap[index] = order++;
        }
      }

      _nextPhotoOrder = order;
      photoSelectionNotifier.value = SelectionState(
        selectedIndexes: selectedIndexes,
        orderMap: orderMap,
      );
      selectedPhotoIndexes = selectedIndexes;
    }

    if (widget.initialSelectedVideos.isNotEmpty) {
      final selectedIndexes = <int>[];
      final orderMap = <int, int>{};

      for (final video in widget.initialSelectedVideos) {
        final index = videoList.indexWhere((v) => v.id == video.id);
        if (index != -1) {
          selectedIndexes.add(index);
          orderMap[index] = 1;
        }
      }

      _nextVideoOrder = selectedIndexes.length + 1;
      videoSelectionNotifier.value = SelectionState(
        selectedIndexes: selectedIndexes,
        orderMap: orderMap,
      );
      selectedVideoIndexes = selectedIndexes;
    }
  }

  void _selectPhoto(int index) {
    final currentState = photoSelectionNotifier.value;
    final currentList = List<int>.from(currentState.selectedIndexes);
    final currentOrder = Map<int, int>.from(currentState.orderMap);

    if (currentList.contains(index)) {
      currentList.remove(index);
      final removedOrder = currentOrder[index]!;
      currentOrder.remove(index);

      final updatedOrder = <int, int>{};
      for (final entry in currentOrder.entries) {
        if (entry.value > removedOrder) {
          updatedOrder[entry.key] = entry.value - 1;
        } else {
          updatedOrder[entry.key] = entry.value;
        }
      }
      currentOrder.clear();
      currentOrder.addAll(updatedOrder);
      _nextPhotoOrder--;
    } else if (widget.networkImageCount + currentList.length < maxPhotoSelect) {
      currentList.add(index);
      currentOrder[index] = _nextPhotoOrder;
      _nextPhotoOrder++;
    }

    photoSelectionNotifier.value = SelectionState(
      selectedIndexes: currentList,
      orderMap: currentOrder,
    );
    selectedPhotoIndexes = currentList;
  }

  void _selectVideo(int index) {
    final currentState = videoSelectionNotifier.value;
    final currentList = List<int>.from(currentState.selectedIndexes);
    final currentOrder = Map<int, int>.from(currentState.orderMap);

    if (currentList.contains(index)) {
      currentList.remove(index);
      currentOrder.clear();
      _nextVideoOrder = 1;
    } else if (currentList.length < maxVideoSelect) {
      currentList.clear();
      currentOrder.clear();
      currentList.add(index);
      currentOrder[index] = _nextVideoOrder;
      _nextVideoOrder = 2;
    }

    videoSelectionNotifier.value = SelectionState(
      selectedIndexes: currentList,
      orderMap: currentOrder,
    );
    selectedVideoIndexes = currentList;
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.black,
          elevation: 0,
          leading: BackButton(color: Colors.white),
          title: Text('Recent project', style: TextStyle(color: Colors.white)),
          centerTitle: true,
          bottom: TabBar(
            indicatorColor: Colors.white,
            labelColor: Colors.white,
            unselectedLabelColor: Colors.white54,
            onTap: (i) => setState(() => tabIndex = i),
            tabs: [
              Tab(text: 'Photos'),
              Tab(text: 'Videos'),
            ],
          ),
        ),
        body: isLoading
            ? Center(child: CircularProgressIndicator())
            : Stack(
                children: [
                  TabBarView(
                    physics: NeverScrollableScrollPhysics(),
                    children: [
                      ValueListenableBuilder<SelectionState>(
                        valueListenable: photoSelectionNotifier,
                        builder: (context, selectionState, child) {
                          return RepaintBoundary(
                            child: OptimizedMediaGrid(
                              key: ValueKey('photos_grid_${photoList.length}'),
                              mediaList: photoList,
                              selectedIndexes: selectionState.selectedIndexes,
                              orderMap: selectionState.orderMap,
                              maxSelect: maxPhotoSelect,
                              isVideo: false,
                              onTap: _selectPhoto,
                              networkImageCount: widget.networkImageCount,
                            ),
                          );
                        },
                      ),
                      ValueListenableBuilder<SelectionState>(
                        valueListenable: videoSelectionNotifier,
                        builder: (context, selectionState, child) {
                          return RepaintBoundary(
                            child: OptimizedMediaGrid(
                              key: ValueKey('videos_grid_${videoList.length}'),
                              mediaList: videoList,
                              selectedIndexes: selectionState.selectedIndexes,
                              orderMap: selectionState.orderMap,
                              maxSelect: maxVideoSelect,
                              isVideo: true,
                              onTap: _selectVideo,
                              networkImageCount: 0,
                            ),
                          );
                        },
                      ),
                    ],
                  ),
                  ValueListenableBuilder<SelectionState>(
                    valueListenable: tabIndex == 0
                        ? photoSelectionNotifier
                        : videoSelectionNotifier,
                    builder: (context, selectionState, child) {
                      if (selectionState.selectedIndexes.isEmpty)
                        return SizedBox.shrink();

                      final totalPhotoCount = tabIndex == 0
                          ? widget.networkImageCount +
                              selectionState.selectedIndexes.length
                          : selectionState.selectedIndexes.length;

                      return Positioned(
                        bottom: 16,
                        right: 16,
                        child: SafeArea(
                          child: ElevatedButton(
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.red,
                              foregroundColor: Colors.white,
                              shape: StadiumBorder(),
                              padding: EdgeInsets.symmetric(
                                  horizontal: 24, vertical: 12),
                            ),
                            onPressed: () {
                              List<AssetEntity> selectedPhotos =
                                  photoSelectionNotifier.value.selectedIndexes
                                      .map((index) => photoList[index])
                                      .toList();
                              List<AssetEntity> selectedVideos =
                                  videoSelectionNotifier.value.selectedIndexes
                                      .map((index) => videoList[index])
                                      .toList();

                              if (widget.isFromPublishPage) {
                                Navigator.pop(context, {
                                  'photos': selectedPhotos,
                                  'videos': selectedVideos,
                                });
                              } else {
                                Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => PublishPage(
                                      selectedPhotos: selectedPhotos,
                                      selectedVideos: selectedVideos,
                                      taskConfigId: widget.taskConfigId,
                                      taskRecordId: widget.taskRecordId,
                                      loadDraftOnInit: false,
                                    ),
                                  ),
                                );
                              }
                            },
                            child: Text(
                              tabIndex == 0
                                  ? 'NEXT ($totalPhotoCount/$maxPhotoSelect)'
                                  : 'NEXT (${selectionState.selectedIndexes.length}/$maxVideoSelect)',
                              style: TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                      );
                    },
                  ),
                ],
              ),
      ),
    );
  }
}

class SelectionState {
  final List<int> selectedIndexes;
  final Map<int, int> orderMap;

  SelectionState({
    required this.selectedIndexes,
    required this.orderMap,
  });

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    return other is SelectionState &&
        _listEquals(selectedIndexes, other.selectedIndexes) &&
        _mapEquals(orderMap, other.orderMap);
  }

  @override
  int get hashCode => selectedIndexes.hashCode ^ orderMap.hashCode;

  bool _listEquals<T>(List<T>? a, List<T>? b) {
    if (a == null) return b == null;
    if (b == null || a.length != b.length) return false;
    for (int index = 0; index < a.length; index += 1) {
      if (a[index] != b[index]) return false;
    }
    return true;
  }

  bool _mapEquals<T, U>(Map<T, U>? a, Map<T, U>? b) {
    if (a == null) return b == null;
    if (b == null || a.length != b.length) return false;
    for (final T key in a.keys) {
      if (!b.containsKey(key) || b[key] != a[key]) return false;
    }
    return true;
  }
}
